from fastapi import APIRouter
from models import Cards, CardsQuery, db, CardCreate,CardsQueryDetail
import os
card_router = APIRouter()

path = os.getcwd()
with open(path+'/routers/card/readme.md','r',encoding='utf-8') as f:
    openapi_desc = f.read().split('------')
# 创建借阅证
@card_router.post('/createLibCard', summary='创建借阅卡',tags=["借阅卡相关接口"],description=openapi_desc[0])
async def createLibCard(card: CardCreate):
    # 创建返回值信息的初始值
    success = True  # 是否成功创建
    msg = "创建成功"  # 返回信息
    # 判断身份证号是否重复
    res = db.cards.find({"reader_id": card.reader_id})
    for it in res:
        success = False
        msg = '该身份证号已被注册'
    # 判断手机号是否重复
    res = db.cards.find({"phone_num": card.phone_num})
    for it in res:
        success = False
        msg = '该手机号已被注册'
    # 补全属性
    # TODO 这种补全模型的方法很危险，绕开了pydantic的类型检查，亟待优化
    cardModel = card.dict(by_alias=True)
    print(type(cardModel))
    cardModel["max_borr"] = 3
    cardModel["debt_count"] = 0
    cardModel["available_status"] = True
    # 如果验证通过则创建
    if success:
        ret = db.cards.insert_one(cardModel)
    return {'success': success, 'msg': msg}
    
# 模糊查询借阅证信息
@card_router.post("/queryLibCard", summary='查找借阅证',tags=["借阅卡相关接口"],description=openapi_desc[1])
async def queryLibCard(card: CardsQuery):
    page = card.page
    size = card.size
    skip = size * (page - 1)
    # 返回数据总条数
    dataCount = db.cards.find({"reader_name": {'$regex': card.reader_name},
                               "reader_sex": {'$regex': card.reader_sex},
                               "unit_name": {'$regex': card.unit_name},
                               "reader_type": {'$regex': card.reader_type},
                               "card_id": {'$regex': card.card_id},
                               "phone_num": {'$regex': card.phone_num}}).count()
    # 返回查询结果
    res = db.cards.find({"reader_name": {'$regex': card.reader_name},
                         "reader_sex": {'$regex': card.reader_sex},
                         "unit_name": {'$regex': card.unit_name},
                         "reader_type": {'$regex': card.reader_type},
                         "card_id":{'$regex':  card.card_id},
                         "phone_num": {'$regex': card.phone_num}}).limit(size).skip(skip)
    cards = []
    for it in res:
        # print(it)
        # print(type(it))
        cardData = Cards(**it)
        cards.append(cardData)
    # 解析结构，并添加到数组中
    return {'data': cards, 'data_count': dataCount}



# 删除借阅卡信息
@card_router.get('/deleteCard', summary='删除借阅卡信息',tags=["借阅卡相关接口"],description=openapi_desc[2])
async def deleteCard(card_id: str):
    success= True
    msg = "删除成功"
    card=db.cards.find_one({"card_id":card_id})
    if card:
        card=Cards(**card)
        if card.available_status:
            db.cards.delete_one({"card_id":card_id})
        else:
            msg="借阅卡不可用"
            success=False
    else:
        msg="查无此卡"
        success=False
    return {'success': success,"msg":msg}

# 详细查找借阅卡信息
@card_router.get("/LibCardDetail",summary="查询借阅证详细信息",tags=["借阅卡相关接口"],description=openapi_desc[3])
async def libCardDetail(card_id:str):
    res = db.cards.find_one({"card_id":card_id})
    if res:
        dataCount = db.borrow_info.find({"card_id":  card_id,"return_status": False}).count()
        res.pop("_id")
        res["borr_num"]=(str)(dataCount)
    return {'data': [res]}

# 查询该卡已借的书
@card_router.get('/getLentBook',summary='查询该卡已借的书',tags=["借阅卡相关接口"],description=openapi_desc[4])
async def getLentBook(card_id: str):
    res=db.borrow_info.find({"card_id": card_id,"return_status": False},{"_id":0,"book_id":1,"book_name":1,"borr_date":1,"due_date":1})
    res=(list(res))
    return{'data':res}
